/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.common.filters;

import com.pingan.haofang.searchcloud.common.constants.Constants;
import com.pingan.haofang.searchcloud.common.constants.ProfileConstant;
import com.pingan.haofang.searchcloud.user.service.SearchProjectService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 搜索API
 *
 * @author ZHANGBI617
 * @date 2017/3/22
 * @since 1.0.0
 */
@Service
@Profile("!" + ProfileConstant.MOCK_API_AUTH)
public class SearchApiAuthorizationFilter extends OncePerRequestFilter {

    private static final String TOKEN_KEY = "token";
    private static final String APP_CODE = "appCode";
    private static final String TRACE_ID = "traceId";

    @Autowired
    private SearchProjectService searchProjectService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        // 校验TRACE_ID
        if (request.getHeader(TRACE_ID) == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "header traceId is null");
            return;
        }

        MDC.put(Constants.TRACE_ID, request.getHeader(TRACE_ID));
        try {
            // 校验参数正确性
            if (request.getHeader(APP_CODE) == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "header appId is null");
                return;
            }
            if (request.getHeader(TOKEN_KEY) == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "header token is null");
                return;
            }

            // 校验TOKEN匹配
            String requestAppCode = request.getHeader(APP_CODE);
            String token = searchProjectService.getTokenByProjectCode(requestAppCode);
            if (!StringUtils.equalsIgnoreCase(token, request.getHeader(TOKEN_KEY))) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "token is not match");
                return;
            }
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(Constants.TRACE_ID);
        }


    }
}
